package so.shanku.essential.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonMapOrListJsonMap2JsonUtil;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.ShopCartAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/9/19 0019.
 * 购物车
 */
public class ShopCartActivity extends BaseUIActivity implements ShopCartAdapter.OnItemClickListener {

	private static final int MAX_NUM = 999;
	/**
	 * 底部全选
	 */
	@ViewInject(id = R.id.totle_selected_cb, click = "totle_selected_cb_click")
	private TextView totle_selected_id;
	/**
	 * 显示总价格
	 */
	@ViewInject(id = R.id.totle_money_tv)
	private TextView totle_money;
	/**
	 * 结算
	 */
	@ViewInject(id = R.id.ensure_order_tv, click = "ensure_order_tv_click")
	private TextView ensure_order_tv;
	/**
	 * 商品的列表页
	 */
	@ViewInject(id = R.id.goods_list)
	private ListView goods_list;
	@ViewInject(id = R.id.nodata_layout)
	private LinearLayout nodata_layout;

	private ShopCartAdapter shopCartAdapter;

	/**
	 * 总价格
	 */
	private double totleMoney;
	private JsonMap datas;

	private boolean isRequestData = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shopcart_layout);
		setCenter_title(R.string.shopcart);
		setBtn_menuText(R.string.delete, getData_deleteToUserCart);

		getServerData();
	}


	@Override
	protected void onRestart() {
		super.onRestart();
		if (isRequestData) {
			getServerData();
			isRequestData = false;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		isRequestData = false;
	}

	/**
	 * 获取购物车信息
	 */
	private void getServerData() {
		loadingToast.show();
		if (datas != null && datas.size() > 0) {
			datas.clear();
			flushDatas(datas);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("UserAccount", Utils.getUserAccount(this));
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_ShoppingCartByUserAccountList);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.What_ShoppingCartByUserAccountList);
		getDataUtil.getData(queue);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	/**
	 * 通知其他页面 购物车数量改变
	 */
	private void sendShopCartNumChangeBroadCast() {
		sendBroadcast(new Intent(Constant.ACAT_SHOPCARTNUMCHANGE));
	}

	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {
//                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
				if (entity.what == GetDataConfing.What_ShoppingCartByUserAccountList || entity.what == GetDataConfing.What_UpdateShoppingCartListCheckend
						|| entity.what == GetDataConfing.What_shoppingUpdateShoppingCartProductAmountById || entity.what == GetDataConfing.What_UpdateShoppingCartCheckend) {
					JsonMap dataServers = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
					datas = dataServers;
					flushDatas(dataServers);
				} else if (entity.what == GetDataConfing.What_shoppingDeleteShoppingCartProduct) {
					getServerData();
				}
				sendShopCartNumChangeBroadCast();

//                } else {
//                }
			} else {
				ShowGetDataError.showNetError(mContext);
			}
			validateData();
			loadingToast.dismiss();
		}

	};

	private void validateData() {
		if (datas == null || datas.size() == 0) {
			nodata_layout.setVisibility(View.VISIBLE);
			goods_list.setVisibility(View.GONE);
		} else {
			goods_list.setVisibility(View.VISIBLE);
			nodata_layout.setVisibility(View.GONE);
		}
	}

	private void flushDatas(JsonMap dataServers) {
		totle_money.setText(String.format(getString(R.string.totle_money), StringUtil.getFormatMoney(dataServers.getStringNoNull("TotalPrice"))));
		List<JsonMap<String, Object>> goodsList = dataServers.getList_JsonMap("ShoppingCartList");
		shopCartAdapter = new ShopCartAdapter(this);
		shopCartAdapter.setDatas(goodsList);
		goods_list.setAdapter(shopCartAdapter);
		shopCartAdapter.setOnItemClickListener(this);
		totle_selected_id.setSelected(dataServers.getBoolean("CheckendThree"));
		//setListViewHeightBasedOnChildren(goods_list);
		setEnsure_order_tv();
	}

	/**
	 * 底部全选
	 *
	 * @param view
	 */
	public void totle_selected_cb_click(View view) {
		selectBrandStauChange(-1, 0);
	}

	/**
	 * 确认订单
	 *
	 * @param view
	 */
	public void ensure_order_tv_click(View view) {
		if (totleMoney < 0.01) {
			toast.showToast(R.string.shopingcart_empty);
			return;
		}

		if (Utils.getUserLoginStyle(this)) {//&&TextUtils.isEmpty(Utils.getUserPhone(this))
			isRequestData = true;
			gotoLogin();
			return;
		}
		List<JsonMap<String, Object>> brandGoodsList = datas.getList_JsonMap("ShoppingCartList");
		List<JsonMap<String, Object>> orderList = new ArrayList<JsonMap<String, Object>>();
		boolean isAllValidate = true;
		for (JsonMap brandGoods : brandGoodsList) {
			List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("ShoppingCartList");
			for (JsonMap jsonMap : goodsList) {
				if (jsonMap.getBoolean("IsCheck")) {
					orderList.add(jsonMap);
					if (!jsonMap.getBoolean("isEnable")) {
						isAllValidate = false;
						break;
					}
				}
			}
		}
		if (!isAllValidate) {
			toast.showToast(R.string.shopcart_container_invalidate);
			return;
		}
		JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
		Intent intent = new Intent(this, ShoppingAddOrderActivity.class);
		intent.putExtra(ExtraKeys.Key_Msg1, totleMoney);
		intent.putExtra(ExtraKeys.Key_Msg2, util.listJsonMap2Json(orderList));
//		zongjia = intent.getDoubleExtra(ExtraKeys.Key_Msg1, 0.00);
//		selectProJson = intent.getStringExtra(ExtraKeys.Key_Msg2);
//
		startActivityForResult(intent, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			getServerData();
		}
	}

	public void setEnsure_order_tv() {
		try {
			totleMoney = Double.parseDouble(datas.getStringNoNull("TotalPrice"));
			ensure_order_tv.setEnabled(true);

		} catch (NumberFormatException e) {
			e.printStackTrace();
			ensure_order_tv.setEnabled(false);
		}
	}

	String orderIdList = "";

	/**
	 * 已登陆的用户将要删除的购物信息加入到发往服务器
	 */
	private View.OnClickListener getData_deleteToUserCart = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (datas == null) {
				return;
			}
			List<JsonMap<String, Object>> brandGoodsList = datas.getList_JsonMap("ShoppingCartList");
			orderIdList = "";
			for (JsonMap brandGoods : brandGoodsList) {
				List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("ShoppingCartList");
				for (JsonMap jsonMap : goodsList) {
					if (jsonMap.getBoolean("IsCheck")) {
						String orderId = jsonMap.getStringNoNull("Id");
						orderIdList = orderId + "," + orderIdList;
					}
				}
			}
			if (TextUtils.isEmpty(orderIdList)) {
				return;
			}
			orderIdList = orderIdList.substring(0, orderIdList.lastIndexOf(","));
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(R.string.shopping_prompt);
			builder.setMessage(R.string.shopping_confirm_delete);
			builder.setPositiveButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface arg0, int arg1) {
						}
					});
			builder.setNegativeButton(R.string.ensure,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							deleteShopGoods();
						}
					});
			builder.show();
		}
	};

	/**
	 * 删除善品
	 */
	private void deleteShopGoods() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(
				GetDataQueue.Params_key,
				GetDataConfing.Key_shoppingDeleteShoppingCartProduct);
		params.put("SptrId", orderIdList);

		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_shoppingDeleteShoppingCartProduct);
		queue.setCallBack(callBack);
		queue.setParamsNoJson(params);
		queue.setWhat(GetDataConfing.What_shoppingDeleteShoppingCartProduct);
		getDataUtil.getData(queue);
	}

	@Override
	public void onItemClick(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {
		if (shopCartitemType == Constant.ShopCartItemCompontType.SELECT_GOODS_BRAND) {
			selectBrandStauChange(position, 1);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.SELECT_GOODS_ITEM) {
			selectStauChange(position, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
			goodsNumChange(position, shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.SUB_NUM) {
			goodsNumChange(position, shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.NUM_EDIT) {
			showEditNumDialog(position, shopCartitemType, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.CLICK_GOODS_ITEM) {
			showGoodsDetail(position, index);
		} else if (shopCartitemType == Constant.ShopCartItemCompontType.CLICK_BRAND_NAME) {
			showBrandDetail(position, index);
		}
	}

	/**
	 * 跳转到店铺详情页
	 *
	 * @param position
	 * @param index
	 */
	private void showBrandDetail(int position, int index) {
		List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("ShoppingCartList");
		JsonMap jsonMap = goodsList.get(position);
		String vendorId = jsonMap.getStringNoNull("VendorId");
		String vendorName = jsonMap.getStringNoNull("ShopName");
		seeShopThemeDetail(vendorId);
	}

	/**
	 * 跳转到商品详情
	 *
	 * @param position
	 * @param index
	 */
	private void showGoodsDetail(int position, int index) {
		List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("ShoppingCartList");
		JsonMap jsonMap = goodsList.get(position).getList_JsonMap("ShoppingCartList").get(index);
		Bundle bundle = new Bundle();
		bundle.putString(Constant.ID, jsonMap.getStringNoNull("ProductId"));
		//bundle.putString(Constant.NAME,jsonMap.getStringNoNull("ShopName"));
		jumpTo(ProductDetailActivity.class, bundle, false);
	}

	/**
	 * 一级或者二级列表 状态改变
	 *
	 * @param position
	 * @param i        0：一级 底部选项 1:2级
	 */
	private void selectBrandStauChange(int position, int i) {
		List<JsonMap<String, Object>> brandGoodsList = datas.getList_JsonMap("ShoppingCartList");


		List<JsonMap<String, Object>> orderList = new ArrayList<JsonMap<String, Object>>();
		int isCheck = 0; //1是全不选否则就全选
		if (i == 1) {
			List<JsonMap<String, Object>> goodsList = brandGoodsList.get(position).getList_JsonMap("ShoppingCartList");
			if (brandGoodsList.get(position).getBoolean("CheckendTheSecond")) {
				isCheck = 1;
			} else {
				isCheck = 0;
			}
			for (JsonMap jsonMap : goodsList) {
				String orderId = jsonMap.getStringNoNull("Id");
				JsonMap jsonMap1 = new JsonMap<String, Object>();
				jsonMap1.put("id", orderId);
				orderList.add(jsonMap1);
			}
		} else {
			if (datas.getBoolean("CheckendThree")) {
				isCheck = 1;
			} else {
				isCheck = 0;
			}
			for (JsonMap brandGoods : brandGoodsList) {
				List<JsonMap<String, Object>> goodsList = brandGoods.getList_JsonMap("ShoppingCartList");
				for (JsonMap jsonMap : goodsList) {
					String orderId = jsonMap.getStringNoNull("Id");
					JsonMap jsonMap1 = new JsonMap<String, Object>();
					jsonMap1.put("id", orderId);
					orderList.add(jsonMap1);
				}
			}
		}

		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("userAccount", Utils.getUserAccount(this));
		params.put("CheckendVO", orderList);
		params.put("Check", isCheck);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_UpdateShoppingCartCheckend);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.What_UpdateShoppingCartCheckend);
		getDataUtil.getData(queue);
	}

	private Dialog dialogLogin;
	private EditText et_product_pronum;
	private ImageView iv_pronum_jian;
	private ImageView iv_pronum_jia;
	private ImageView bt_quxiao;
	private ImageView bt_queding;
	private TextView tv_price;
	private TextView tv_pronum;
	int pronum;
	private String orderId;

	private void showEditNumDialog(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {
		List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("ShoppingCartList");
		JsonMap jsonMap = goodsList.get(position).getList_JsonMap("ShoppingCartList").get(index);
		orderId = jsonMap.getStringNoNull("Id");
		dialogLogin = new Dialog(this, R.style.ShopDialogStyle);
		dialogLogin.setCanceledOnTouchOutside(false);
		dialogLogin.setCancelable(true);
		View view = getLayoutInflater().inflate(R.layout.item_shoppingcart_editnum, null);
		et_product_pronum = (EditText) view
				.findViewById(R.id.i_s_et_product_pronum);
		iv_pronum_jian = (ImageView) view
				.findViewById(R.id.i_s_iv_pronum_jian);
		iv_pronum_jia = (ImageView) view
				.findViewById(R.id.i_s_iv_pronum_jia);
		bt_quxiao = (ImageView) view
				.findViewById(R.id.i_s_bt_quxiao);
		bt_queding = (ImageView) view
				.findViewById(R.id.i_s_bt_queding);
		tv_price = (TextView) view
				.findViewById(R.id.i_s_tv_price);
		tv_pronum = (TextView) view
				.findViewById(R.id.i_s_tv_pronum);
		dialogLogin.setContentView(view);

		tv_price.setText(StringUtil.getFormatMoneyWithSign(jsonMap.getStringNoNull("ProductPrice")));
		et_product_pronum.setText(jsonMap.getStringNoNull("Amount"));
		tv_pronum.setVisibility(View.GONE);
		// tv_pronum.setText("x" + et_product_pronum.getText());
		dialogLogin.show();

		iv_pronum_jia.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				pronum = Integer.parseInt(et_product_pronum
						.getText().toString());
				if (pronum < MAX_NUM) {
					pronum = pronum + 1;
				}
//								pronum = 1000;
				show();
			}
		});
		iv_pronum_jian
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						pronum = Integer
								.parseInt(et_product_pronum
										.getText().toString());
						if (pronum > 1) {
							pronum = pronum - 1;
						}
						show();
					}
				});
		bt_quxiao.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogLogin.cancel();
			}
		});

		bt_queding.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!"".equals(et_product_pronum.getText()
						.toString())) {
					pronum = Integer.parseInt(et_product_pronum
							.getText().toString());
					if (pronum > 0) {
						dialogLogin.cancel();
						updateGoodsNum(pronum, orderId);
					}
				}

			}
		});
	}

	public void show() {
		et_product_pronum.setText(pronum + "");
		// tv_pronum.setText(pronum + "");
	}

	private void goodsNumChange(int position, Constant.ShopCartItemCompontType shopCartitemType, int index) {

		List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("ShoppingCartList");
		JsonMap jsonMap = goodsList.get(position).getList_JsonMap("ShoppingCartList").get(index);
		int num = jsonMap.getInt("Amount");
		if (shopCartitemType == Constant.ShopCartItemCompontType.ADD_NUM) {
			if (num >= MAX_NUM) {
				return;
			}
			num++;
		} else {
			if (num <= 1) {
				return;
			}
			num--;
		}
		//String productId = jsonMap.getStringNoNull("ProductId");
		orderId = jsonMap.getStringNoNull("Id");
		updateGoodsNum(num, orderId);
	}

	/**
	 * 更新数量
	 *
	 * @param num
	 * @param productId 订单编号
	 */
	private void updateGoodsNum(int num, String productId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key,
				GetDataConfing.Key_shoppingUpdateShoppingCartProductAmountById);
		// params.put("userAccount", app.getUserId());
		params.put("Id", productId);
		params.put("Amount", num);
		params.put("userName", Utils.getUserAccount(this));
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.Action_shoppingUpdateShoppingCartProductAmountById);
		queue.setCallBack(callBack);
		queue.setParamsNoJson(params);
		queue.setWhat(GetDataConfing.What_shoppingUpdateShoppingCartProductAmountById);
		getDataUtil.getData(queue);
	}

	/**
	 * 商品状态的变化 {CheckendVO:[{id:80450},{id:80456}]}
	 *
	 * @param position
	 * @param index
	 */
	private void selectStauChange(int position, int index) {
		List<JsonMap<String, Object>> goodsList = datas.getList_JsonMap("ShoppingCartList");
		String orderId = goodsList.get(position).getList_JsonMap("ShoppingCartList").get(index).getStringNoNull("Id");

		List<JsonMap<String, Object>> orderList = new ArrayList<JsonMap<String, Object>>();
		JsonMap jsonMap = new JsonMap<String, Object>();
		jsonMap.put("id", orderId);
		orderList.add(jsonMap);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("userAccount", Utils.getUserAccount(this));
		params.put("CheckendVO", orderList);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_UpdateShoppingCartListCheckend);
		queue.setParamsNoJson(params);
		queue.setCallBack(callBack);
		queue.setWhat(GetDataConfing.What_UpdateShoppingCartListCheckend);
		getDataUtil.getData(queue);
	}
}